// 打印类属性、方法定义
/* eslint-disable */
const globalData = {
	baseUrl: '/dms',
	// baseUrl : "/supplyx-mes",
	baseAuthUrl: '/supplyx-mes',
	baseUploadUrl: '/upload',
	baseDmsUrl: '/dms',
};
import request from '@/axios/axios.js';
import { Message } from 'element-ui';
const baseUrl = 'http://121.228.40.79:1666';
// 上传功能
const Print = function (dom, options) {
	if (!(this instanceof Print)) return new Print(dom, options);

	this.options = this.extend(
		{
			noPrint: '.no-print',
		},
		options
	);

	if (typeof dom === 'string') {
		this.dom = document.querySelector(dom);
	} else {
		this.isDOM(dom);
		this.dom = this.isDOM(dom) ? dom : dom.$el;
	}

	this.init();
};
Print.prototype = {
	init: function () {
		var content = this.getStyle() + this.getHtml();
		this.writeIframe(content);
	},
	extend: function (obj, obj2) {
		for (var k in obj2) {
			obj[k] = obj2[k];
		}
		return obj;
	},

	getStyle: function () {
		var str = '',
			styles = document.querySelectorAll('style,link');
		if (this.options.style && this.options.style == 'self') {
			if (this.options.selectorText) {
				let styleText = this.getCssBlock(this.options.selectorText);
				str += '<style>' + styleText + '</style>';
			} else {
				let style = this.dom.querySelector('.style-label');
				str += '<style>' + style.innerText + '</style>';
			}
		} else {
			for (var i = 0; i < styles.length; i++) {
				str += styles[i].outerHTML;
			}
		}
		str += '<style>' + (this.options.noPrint ? this.options.noPrint : '.no-print') + '{display:none;}</style>';

		return str;
	},

	getHtml: function () {
		var inputs = document.querySelectorAll('input');
		var textareas = document.querySelectorAll('textarea');
		var selects = document.querySelectorAll('select');

		for (var k = 0; k < inputs.length; k++) {
			if (inputs[k].type == 'checkbox' || inputs[k].type == 'radio') {
				if (inputs[k].checked == true) {
					inputs[k].setAttribute('checked', 'checked');
				} else {
					inputs[k].removeAttribute('checked');
				}
			} else if (inputs[k].type == 'text') {
				inputs[k].setAttribute('value', inputs[k].value);
			} else {
				inputs[k].setAttribute('value', inputs[k].value);
			}
		}

		for (var k2 = 0; k2 < textareas.length; k2++) {
			if (textareas[k2].type == 'textarea') {
				textareas[k2].innerHTML = textareas[k2].value;
			}
		}

		for (var k3 = 0; k3 < selects.length; k3++) {
			if (selects[k3].type == 'select-one') {
				var child = selects[k3].children;
				for (var i in child) {
					if (child[i].tagName == 'OPTION') {
						if (child[i].selected == true) {
							child[i].setAttribute('selected', 'selected');
						} else {
							child[i].removeAttribute('selected');
						}
					}
				}
			}
		}
		var clone = this.dom.cloneNode(true);
		clone.removeAttribute('hidden');
		return clone.outerHTML;
	},
	getCssBlock: function (selectorText) {
		const cssBlock = document.styleSheets;
		const styleData = [...cssBlock].reverse().find(({ cssRules }) => {
			return [...cssRules].find((rule) => {
				return rule.selectorText.indexOf(selectorText) != -1;
			});
		});
		return styleData.ownerNode.innerText;
	},
	writeIframe: function (content) {
		var w,
			doc,
			iframe = document.createElement('iframe'),
			f = document.body.appendChild(iframe);
		iframe.id = 'myIframe';
		//iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
		iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;');
		w = f.contentWindow || f.contentDocument;
		doc = f.contentDocument || f.contentWindow.document;
		doc.open();
		doc.write(content);
		doc.close();
		var _this = this;
		iframe.onload = function () {
			_this.toPrint(w);
			setTimeout(function () {
				document.body.removeChild(iframe);
			}, 100);
		};
	},

	toPrint: function (frameWindow) {
		try {
			setTimeout(function () {
				frameWindow.focus();
				try {
					if (!frameWindow.document.execCommand('print', false, null)) {
						frameWindow.print();
					}
				} catch (e) {
					frameWindow.print();
				}
				frameWindow.close();
			}, 10);
		} catch (err) {
			console.log('err', err);
		}
	},
	isDOM:
		typeof HTMLElement === 'object'
			? function (obj) {
					return obj instanceof HTMLElement;
			  }
			: function (obj) {
					return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
			  },
};

const MyPlugin = {};

// 默认打印标签
const defaultLabel = {
	// 物料二维码标签打印
	materialBarcodePrint: '/print/default/MaterialBarcodePrint_Default',
	// 设备标签打印
	equipmentPrint: '/print/default/EquipmentPrint_Default',
	// 入库箱单标签打印
	inorderBarcodePrint: '/print/default/InorderBarcodePrint_Default',
	// 送货清单标签打印
	deliverListPrint: '/print/default/InorderListPrint_Default',
	// 工单任务打印
	workorderPrint: '/print/default/WorkorderPrint_Default',
	// 报工标签打印
	workorderReportPrint: '/print/default/WorkorderReportPrint_Default',
	// 计划任务
	planBarcodePrint: '/print/default/PlanBarcodePrint_Default',
	//工序流转卡打印
	processFlowCardPrint: '/print/default/ProductplanOutProcessPrint_Default',
	//NCR打印
	ncrPrint: '/PrivateCloud/UTC-MES/NCReport.cpt',
	//流转卡补打
	FlowCardMakeUpPrint: '/PrivateCloud/UTC-MES/ProductplanOutProcessPrint_repair.cpt',
	//原材料追溯打印模板
	RawMaterialPrint: '/PrivateCloud/UTC-MES/testYan.cpt',
	//生产追溯打印模板
	proTraceabilityCodePrint: '/PrivateCloud/UTC-MES/WorkorderMaterial.cpt',
	//生成7位追溯码打印
	generateTraceabilityCodePrint: '/PrivateCloud/UTC-MES/WorkorderReportMaterialShort.cpt',
	//库存箱标签打印模板
	stockBoxLabelPrint: '/print/default/StockBarcodePrint_Default',
	//库位码打印模板
	LocationCodePrint: '/tsPrinttemplate/printInfoPc',
	//客户标签-外箱编号打印
	DeliveryplanTagPrint: '/PrivateCloud/UTC-MES/DeliveryplanTagPrint.cpt',
	DeliveryplanTagPrint01: '/PrivateCloud/UTC-MES/DeliveryplanTagPrint_11369.cpt', //外箱标签打印客户11369
	DeliveryplanTagPrint02: '/PrivateCloud/UTC-MES/DeliveryplanTagPrint_11375.cpt', //外箱标签打印客户11375
	DeliveryplanTagPrint03: '/PrivateCloud/UTC-MES/DeliveryplanTagPrint_10326.cpt', //外箱标签打印客户10326
	//委外单据打印
	OutsourcePlanPrint: '/PrivateCloud/UTC-MES/OutsourcePlanPrint.cpt',
	//工单任务补打
	workReplenishPrint: '/PrivateCloud/UTC-MES/WorkorderTaskReplenish.cpt',
	//工单任务派工-任务打印
	WorkorderTaskReplenish: '/PrivateCloud/UTC-MES/WorkorderTaskReplenish_Default.cpt',
	//生产追溯码尾箱打印
	WorkorderReportMaterialTrunk: '/PrivateCloud/UTC-MES/WorkorderReportMaterialTrunk.cpt',
	//报工总数打印
	workorderReportMaterialCount: '/PrivateCloud/UTC-MES/WorkorderReportMaterialCount.cpt',
	//生产追溯码  包装尾箱打印
	packingBootPrinting: '/PrivateCloud/UTC-MES/WorkorderReportMaterialTailBox.cpt',
	//	履历卡打印
	resumeCardPrint: '/PrivateCloud/UTC-MES/ToolingResume.cpt',
	subcontractingPrint: '/PrivateCloud/UTC-MES/OutsourcingMaterialReturn.cpt', //委外退料单打印
	repertoryDetailReportNumPrint: '/PrivateCloud/UTC-MES/TtStockBarcodePrintCount.cpt', //库存明细报工总数打印
	repertoryDetailMakeup: '/PrivateCloud/UTC-MES/TtStockBarcodePrint.cpt', //库存明细追溯码补打
	repertoryDetailProTraceability: '/PrivateCloud/UTC-MES/TtStockBarcodePrintTrunk.cpt', //库存明细生产追溯码尾箱打印
	repertoryDetailpackingBootPrint: '/PrivateCloud/UTC-MES/TtStockBarcodePrintTailBox.cpt', //库存明细包装尾箱打印
	InorderBoxLabelPrint: '/PrivateCloud/UTC-MES/InorderBoxLabelPrint.cpt', //入库订单箱标签打印
	qualityResultsPrint: '/PrivateCloud/UTC-MES/TtTestitemPrint_Default.cpt', //质检结果打印
	MaterialRequisitionPrint: '/PrivateCloud/UTC-MES/MaterialRequisitionPrint.cpt', //领料单打印
	WithdrawalOrderPrint: '/PrivateCloud/UTC-MES/WithdrawalOrderPrint.cpt', //退(好)线单打印
	WithdrawalOrderPrint_Ncr: '/PrivateCloud/UTC-MES/WithdrawalOrderPrint_Ncr.cpt', //退(NCR)线单打印
	toolingIssueLabelPrint: '/PrivateCloud/UTC-MES/EquipmentToolingPrint.cpt', //工装出库标签打印
};
const templateTypeDict = {
	equipmentPrint: '001', //设备标签打印模板
	inorderBarcodePrint: '002', //原材料收货标签打印模板
	pickListPrint: '003', //拣货清单打印模板
	processFlowCardPrint: '004', //工序流转卡打印模板
	workorderPrint: '005', //工单任务打印模板
	workorderReportPrint: '006', //报工标签打印模板
	deliverListPrint: '007', //送货清单打印模板
	planBarcodePrint: '008', //计划任务打印
	deliverPlanReportPrint: '009', //发货计划预捡配单
	materialBarcodePrint: '010', //物料标签打印模板
	materialGroupPrint: '011', //来料组托标签打印模板
	stockGroupPrint: '012', //库内组托标签打印模板
	produceGroupPrint: '013', //生产组托标签打印模板
	deliverListPrint: '014', //发货清单打印模板
	inStockLablePrint: '015', //入库标签批量打印
	outStockLablePrint: '016', //出库标签批量打印
	plletListReportPrint: '017', //托盘清单报表_调拨
	entruckListPrint: '018', //装车清单打印模板
	stockBoxLabelPrint: '019', //装车清单打印模板
	ncrPrint: '019', //NCR打印
	FlowCardMakeUpPrint: '020', //流转卡补打
	RawMaterialPrint: '021', //原材料追溯打印模板
	// proTraceabilityCodePrint: '022', //生产追溯打印模板
	proTraceabilityCodePrint: '099', //二期生产追溯打印模板
	stockBoxLabelPrint: '023', //库存箱标签打印模板
	LocationCodePrint: '024', //库位码打印模板
	DeliveryplanTagPrint: '025', //外箱标签打印客户6881
	OutsourcePlanPrint: '026', //委外单据打印
	DeliveryplanTagPrint01: '027', //外箱标签打印客户11369
	DeliveryplanTagPrint02: '028', //外箱标签打印客户11375
	DeliveryplanTagPrint03: '029', //外箱标签打印客户10326
	workReplenishPrint: '030', //工单任务补打
	WorkorderOutputPrint: '032', //标识卡打印
	WorkorderTaskReplenish: '033', //工单任务派工-任务打印
	WorkorderReportMaterialTrunk: '034', //生产追溯码尾箱打印
	workorderReportMaterialCount: '031', //报工总数打印
	generateTraceabilityCodePrint: '035', //7位追溯码打印
	packingBootPrinting: '036', //生产追溯码  包装尾箱打印
	resumeCardPrint: '037', //	履历卡打印
	subcontractingPrint: '038', //委外退料单打印
	repertoryDetailReportNumPrint: '039', //库存明细报工总数打印
	repertoryDetailMakeup: '040', //库存明细追溯码补打
	repertoryDetailProTraceability: '041', //库存明细生产追溯码尾箱打印
	repertoryDetailpackingBootPrint: '042', //库存明细包装尾箱打印
	InorderBoxLabelPrint: '044', //入库订单箱标签打印
	qualityResultsPrint: '045', //质检结果打印
	MaterialRequisitionPrint: '046', //领料单打印
	WithdrawalOrderPrint: '047', //退(好)线单打印
	WithdrawalOrderPrint_Ncr: '048', //退(NCR)线单打印
	toolingIssueLabelPrint: '049', //工装出库标签打印
};
const fineReport = function (options) {
	//options
	// {
	// 	reportlets:[{
	// 	  reportlet:"materialBarcodePrint.cpt",	//打印模板
	// 	  rsp:this.barcodeList	//打印的数据，为数组格式
	// 	}],
	// 	//数字签证
	// 	fine_digital_signature: param.fine_digital_signature,
	// 	// 下面参数暂时无需填写
	// 	printUrl :"http://82.156.22.180:8080/webroot/decision/view/report",
	// 	// 是否弹出设置窗口，true为弹出，false为不弹出
	// 	isPopUp:false,
	// 	printType:0,
	// 	// 以下为零客户端打印的参数，仅当 printType 为 0 时生效
	// 	ieQuietPrint:true,// IE静默打印设置 true为静默，false为不静默
	// 	// 以下为本地打印的参数，仅当 printType 为 1 时生效
	// 	printerName:'Microsoft Print to PDF', // 打印机名
	// 	pageType:0, // 打印页码类型：0：所有页，1：当前页，2：指定页
	// 	pageIndex:"1-2", // 页码范围。当 pageType 为 2 时有效 "1-3"
	// 	copy:1 // 打印份数
	// }
	let re = /\.(cpt)$/;
	options.reportlets.map((item) => {
		if (!re.test(item.reportlet)) {
			item.reportlet += '.cpt';
		}
	});
	let win = document.getElementById('fineReport').contentWindow;
	win.postMessage(options, baseUrl);
};
//获取标签模板
const getPrintTemplate = function (config = {}, params = {}) {
	if (!config.tmPlantId) {
		Message({
			message: '缺少必要的工厂id',
			type: 'error',
			duration: 3 * 1000,
		});
		return Promise.reject({ errMsg: '缺少必要的工厂id' });
	} else if (!config.templateType) {
		Message({
			message: '缺少必要的模板类型',
			type: 'error',
			duration: 3 * 1000,
		});
		return Promise.reject({ errMsg: '缺少必要的模板类型' });
	}
	return new Promise((resolve, reject) => {
		request({
			url: globalData.baseUrl + '/tsPrinttemplate/custom',
			method: 'post',
			data: config,
			params: params,
		})
			.then((res) => {
				if (res.code == 200) {
					if (res.data[0] && res.data[0].printtemplateNo != '') {
						let pattern = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
						let printTemplate = res.data[0].printtemplateNo;
						//如果返回的模板是个url,则取url中的viewlet参数值作为模板名称
						if (pattern.test(printTemplate)) {
							let reg = new RegExp('(^|&)' + 'viewlet' + '=([^&]*)(&|$)', 'i');
							let search = printTemplate.split('?')[1];
							let r = search.match(reg);
							if (r) {
								resolve({
									code: '0',
									template: unescape(r[2]),
								});
							}
						} else {
							resolve({
								code: 0,
								template: printTemplate,
							});
						}
					} else {
						resolve({
							code: 0,
							template: '',
						});
					}
				} else {
					resolve(res);
				}
			})
			.catch((error) => {
				reject(error);
			});
	});
};

const fineReportPrint = function ({ tmPlantId, templateType, ids, search, templatePath, options = {} }) {
	console.log('fineReportPrint');

	if (!ids.length) {
		Message({
			message: '请选择要打印的数据',
			type: 'error',
			duration: 3 * 1000,
		});
		return;
	}
	console.log('fineReportPrint');
	let id = `${JSON.stringify(ids).replace('[', '').replace(']', '')}`;
	let defaultTemplate;
	switch (templateType) {
		case '001':
			defaultTemplate = defaultLabel.equipmentPrint;
			break;
		case '002':
			defaultTemplate = defaultLabel.inorderBarcodePrint;
			break;
		case '003':
			breaak;
		case '004':
			defaultTemplate = defaultLabel.processFlowCardPrint;
			break;
		case '005':
			defaultTemplate = defaultLabel.workorderPrint;
			break;
		case '006':
			defaultTemplate = defaultLabel.workorderReportPrint;
			break;
		case '007':
			defaultTemplate = defaultLabel.deliverListPrint;
			break;
		case '008':
			defaultTemplate = defaultLabel.planBarcodePrint;
			break;
	}
	if (templatePath) {
		// 走的产品包装配置
		if (options.isSplicing) {
			//库存明细查询 委外退料单打印走的  其他的还是按照原来的
			fineReport({
				reportlets: [
					{
						reportlet: templatePath,
						search: search,
						sourceIds: ids.join(','),
						token: options.token,
					},
				],
				reportUrl: baseUrl,
				...options,
			});
		} else {
			console.log(baseUrl, baseUrl);

			fineReport({
				reportlets: [
					{
						reportlet: templatePath,
						search: 'where id in (' + id + ')',
						sourceIds: ids.join(','),
						token: options.token,
					},
				],
				reportUrl: baseUrl,
				...options,
			});
		}
	} else {
		//走的打印模板配置
		getPrintTemplate(
			{
				tmPlantId: tmPlantId,
				templateType: templateType,
			},
			{ loading: true }
		).then((response) => {
			if (response.code == 0 && response.template) {
				fineReport({
					reportlets: [
						{
							reportlet: response.template,
							search: 'where id in (' + id + ')',
							sourceIds: ids.join(','),
							token: options.token,
						},
					],
					reportUrl: baseUrl,
					...options,
				});
			} else {
				fineReport({
					reportlets: [
						{
							reportlet: defaultTemplate,
							search: 'where id in (' + id + ')',
							sourceIds: ids.join(','),
							token: options.token,
						},
					],
					reportUrl: baseUrl,
					...options,
				});
			}
		});
	}
};
const locationWifiPrint = function ({ printParams, template, sourceIds, search }) {
	let params = typeof printParams == 'string' ? JSON.parse(printParams) : printParams;
	if (printParams.isSplicing && printParams.rowData) {
		let a = JSON.stringify(printParams.rowData);
		params.imageUrl = baseUrl + '/webroot/decision/view/report?viewlet=' + template + `&rowData=${a}`;
	} else {
		// params.imageUrl = window.location.href.split('/mes')[0] + '/webroot/decision/view/report?viewlet=' + template;

		params.imageUrl = baseUrl + '/webroot/decision/view/report?viewlet=' + template;
	}
	// params.imageUrl = 'https://mom.goocidata.com/webroot/decision/view/report?viewlet=' + template;
	params.sourceIds = sourceIds; //'0004E08DEC3046D296138030CEAF4B1F,0010C00F8CAA4E2CB5A29531A77B4C6A'
	params.search = search;
	console.log(params.apiUrl,'params.apiUrl');
	request({
		url: params.apiUrl,
		method: 'post',
		data: params,
		params: { loading: true },
	})
		.then((res) => {
			console.log('打印成功');
			// Message({
			// 	message: '打印成功',
			// 	type: 'success',
			// 	duration: 2 * 1000,
			// });
		})
		.catch((error) => {});
};
/**
 * tmPlantId工厂id
 * tmMaterialId物料id
 * tmCustomerId客户id
 * templateType打印类型
 * templatePath打印模板
 * ids打印数据
 * printParams打印参数
 *
 * */
const locationWifiPrinter = function ({
	tmPlantId,
	tmMaterialId,
	tmCustomerId,
	templateType,
	templatePath,
	ids,
	search,
	printParams = {},
	options = {},
}) {
	console.log(!ids.length);
	if (!ids.length) {
		Message({
			message: '请选择要打印的数据',
			type: 'error',
			duration: 3 * 1000,
		});
		return;
	}
	// 打印信息查询
	console.log('打印信息查询');
	request({
		url: globalData.baseUrl + '/printer-template/printInfo',
		method: 'post',
		data: {
			templateType: templateTypeDict[templateType] || templateType,
			tmPlantId: tmPlantId,
			tmMaterialId: tmMaterialId,
			tmCustomerId: tmCustomerId,
		},
		params: {
			loading: true,
		},
	}).then((res) => {
		if (res.code == 200) {
			if (res.data.silent) {
				// 静默打印，配置了默认wiFi打印机
				console.log('静默打印，配置了默认wiFi打印机');
				locationWifiPrint({
					printParams: {
						...res.data,
						...printParams,
					},
					template: templatePath || res.data.template,
					sourceIds: ids.join(','),
					search: search,
					...options,
				});
			} else {
				// 预览打印
				console.log('预览打印');
				fineReportPrint({
					templatePath: templatePath || res.data.template,
					templateType: templateTypeDict[templateType] || templateType,
					tmPlantId: tmPlantId,
					ids: ids,
					search: search,
					options: {
						...printParams,
						...options,
					},
				});
			}
		}
	});
};
MyPlugin.install = function (Vue, options) {
	// 4. 添加实例方法
	Vue.prototype.$print = Print;
	Vue.prototype.$fineReport = fineReport;
	Vue.prototype.$getPrintTemplate = getPrintTemplate;
	Vue.prototype.$fineReportPrint = fineReportPrint;
	Vue.prototype.$defaultLabel = defaultLabel;
	Vue.prototype.$locationWifiPrinter = locationWifiPrinter;
};
export default MyPlugin;
